<template>
    <div class="app-view">
        <transition name="fade-transform" mode="out-in">
            <vxe-grid v-show="!showCreate"
                      id="xGrid"
                      :loading="loading"
                      ref="xGrid"
                      border
                      resizable
                      show-overflow
                      keep-source
                      highlight-hover-row
                      :height="tableH"
                      align="center"
                      :print-config="{}"
                      :import-config="{}"
                      :export-config="{}"
                      :custom-config="{storage: true}"
                      :toolbar-config="tableToolbar"
                      :edit-config="editConfig"
                      :edit-rules="formRules"
                      :columns="tableColumn"
                      :seq-config="{startIndex: (tablePage.currentPage - 1) * tablePage.pageSize}"
                      :pager-config="tablePage"
                      :data="tableData"
                      @page-change="handlePageChange"
                      @edit-closed="editClosed">
                <template v-slot:toolbar_buttons>
                    <div class="tableToolbar">
                        <div style="min-width: 70px; margin-block: auto;" class="tableToolbarText">用户名称：</div>
                        <el-input v-model="searchName" size="mini" placeholder="请输入姓名、用户名或工号查询" clearable class="tableToolbarTextL" style="width: 230px;" @change="getData(0)" />
                        <el-button type="primary" size="mini" class="tableToolbarTextL" @click="create">新增</el-button>
                        <el-button type="primary" size="mini" class="tableToolbarTextL" @click="getData(0)">查询</el-button>
                    </div>
                </template>
                <!-- 状态 -->
                <template #zt="{ row }">
                    <el-tag :type="row.isEnable === true ? 'success' : 'info'" style="width: 60px;">
                        {{ format(userjson.isEnable, row.isEnable) }}
                    </el-tag>
                </template>
                <template #zt_edit="{ row }">
                    <vxe-switch v-model="row.isEnable" open-label="有效" :open-value="true" close-label="无效" :close-value="false" size="small" />
                </template>
                <template #operate="{ row }">
                    <el-link type="primary" class="elLinkBTN" @click="edit(row)">编辑</el-link>
                    <el-link type="danger" class="elLinkBTN" @click="deleteDe(row)">删除</el-link>
                </template>
            </vxe-grid>
        </transition>

        <transition name="fade-transform" mode="out-in">
            <div v-show="showCreate">
                <el-page-header @back="goBack">
                    <div slot="content">
                        {{ formTitle }}
                        <div style="position: absolute;right: 52px;top: 15px;">
                            <vxe-button status="primary" size="small" content="保存" @click="save" />
                        </div>
                    </div>
                </el-page-header>
                <div class="elscrollbar_gg" :style="{'height': (tableH - 44) + 'px'}">
                    <el-scrollbar style="height:100%;margin-top:30px">
                        <div style="max-width: 900px;margin: 20px auto;">
                            <vxe-form ref="myform" :loading="formLoading" :data="formInfo" title-width="90" :items="formItems" :rules="formRules">
                                <template #titleLevel="{ data }">
                                    <vxe-select v-model="data.titleLevel" size="mini" clearable @change="selectTitle">
                                        <vxe-option v-for="item in userjson.titleOption" :key="item.value" :label="item.label" :value="item.value" />
                                    </vxe-select>
                                </template>
                                <template #titleID="{ data }">
                                    <vxe-select v-model="data.titleID" size="mini" clearable>
                                        <vxe-option v-for="item in titleLevelOption" :disabled="data.titleLevel==='' || data.titleLevel===null" :key="item.value" :label="item.label" :value="item.value" />
                                    </vxe-select>
                                </template>
                                
                            </vxe-form>
                        </div>
                    </el-scrollbar>
                </div>
            </div>
        </transition>
    </div>
</template>
<script>
    import baseAPI from '../../request/Base/BaseAPI.js';
    import userjson from '../../common/json/userOption.js';
    export default {
        data() {
            return {
                userjson,
                loading: false,
                positionOption: [],
                searchName: '',
                arrAllRole: [],
                titleOption: [],
                titleLevelOption: [],
                tableH: window.innerHeight - topBarHeight - 80,
                tableColumn: [
                    { type: 'seq', title: '序号', width: 60, fixed: 'left' },
                    { field: 'userName', title: '用户名', fixed: 'left', width: 200 },
                    { field: 'userCode', title: '工号', fixed: 'left', minWidth: 180 },
                    { field: 'realName', title: '姓名', fixed: 'left', minWidth: 180 },
                    //{ field: 'password', title: '密码', fixed: 'left', minWidth: 180 },
                    { field: 'sex', title: '性别', width: 100, formatter: ({ row }) => { return this.format(userjson.sex, row.sex) } },
                    { field: 'roleId', title: '角色', width: 160, },
                    //{ field: 'profName', title: '专业', width: 160, },
                    { field: 'mobile', title: '手机号', minWidth: 180 },
                    { field: 'birthday', title: '出生日期', width: 180, formatter: ({ row }) => { return this.toDate(row.birthday) } },
                    //{ field: 'isEnable', title: '状态', fixed: 'right', width: 100, editRender: {}, slots: { default: 'zt', edit: 'zt_edit' } },
                    { title: '操作', fixed: 'right', width: 160, slots: { default: 'operate' } }
                ],
                editConfig: {
                    enabled: true,
                    trigger: 'click',
                    mode: 'row',
                    showStatus: true
                },
                tableToolbar: {
                    refresh: {
                        query: () => this.getData()
                    },
                    import: false,
                    export: false,
                    print: false,
                    custom: true,
                    slots: {
                        buttons: 'toolbar_buttons'
                    }
                },
                tablePage: {
                    total: 0,
                    currentPage: 1,
                    pageSize: 50,
                    align: 'right',
                    pageSizes: [50, 80],
                    layouts: ['Sizes', 'PrevJump', 'PrevPage', 'JumpNumber', 'NextPage', 'NextJump', 'FullJump', 'Total'],
                    perfect: true
                },
                tableData: [],

                showCreate: false,
                formLoading: false,
                formTitle: '',
                formInfo: {},
                formItems: [
                    { field: 'userName', title: '用户名', span: 24, itemRender: { name: '$input', props: { placeholder: '请填写用户名' } } },
                    { field: 'userCode', title: '工号', span: 24, itemRender: { name: '$input', props: { placeholder: '请填写工号' } } },
                    { field: 'realName', title: '姓名', span: 24, itemRender: { name: '$input', props: { placeholder: '请填写姓名' } } },
                    { field: 'password', title: '密码', span: 24, itemRender: { name: '$input', props: { placeholder: '请输入密码' } } },
                    { field: 'sex', title: '性别', span: 24, itemRender: { name: '$select', options: userjson.sex } },
                    { field: 'roleId', title: '角色', span: 24, itemRender: { name: '$select', options: null } },
                    //{ field: 'profName', title: '专业', span: 24, itemRender: { name: '$select', options: null } },
                    { field: 'birthday', title: '出生日期', span: 24, itemRender: { name: '$input', props: { type: 'date', labelFormat: 'yyyy-MM-dd', placeholder: '请选择出生日期' } } },
                    { field: 'mobile', title: '手机号', span: 24, itemRender: { name: '$input', props: { type: 'number', placeholder: '请填写手机号' } } },
                ],
                formRules: {
                    userName: [{ required: true, message: '请填写用户名' }],
                    userCode: [{ required: false, message: '请填写工号' }],
                    realName: [{ required: true, message: '请填写姓名' }],
                    password: [
                        { required: true, message: '请填写密码' },
                        {pattern: /^.{6,}$/, message: '密码长度不少于6位' }
                        //{
                        //    pattern: "^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])[a-zA-Z0-9]{8,12}$", message: '密码包含大小写字母和数字的组合，不能使用特殊字符，长度在8-12之间!'
                        //}
                    ],
                    //mobile: [{ required: true, message: '请填写手机号' }]
                },
                uploadUrl: '',
                fileList: [],
                formInfoID: null,
                isAdd: false,
                signFrontInfo: '',
            };
        },
        async mounted() {
            //this.uploadUrl = requestURL + '/security/UserSignUpDnld/Upload/';
            //await this.getAllPosition();
            //await this.getAllTitle();
            this.getData(0);
            var _this = this;
            window.onresize = () => {
                return (() => {
                    _this.tableH = window.innerHeight - 80 - 80;
                })();
            };
        },
        beforeDestroy() {
            window.onresize = null;
        },
        methods: {
            visibilityChange() {
                if (document.visibilityState == 'visible') {
                    this.getData();
                }
            },
            getAllPosition() {
                return new Promise((resolve, reject) => {
                    this.positionOption = [];
                    baseAPI.getAllPosition().then(res => {
                        this.formItems[4].itemRender.options = res.map(x => {
                            return { label: x.positionName, value: x.positionID }
                        });
                        this.positionOption = res.map(x => {
                            return { label: x.positionName, value: x.positionID }
                        });
                        resolve();
                    }).catch(() => {
                        resolve();
                    });
                });
            },
            // 获取所有职称
            getAllTitle() {
                return new Promise((resolve, reject) => {
                    this.positionOption = [];
                    baseAPI.getAllTitle().then(res => {
                        this.formItems[4].itemRender.options = res.map(x => {
                            return { label: x.titleName, value: x.titleID }
                        });
                        this.titleOption = res.map(x => {
                            return { label: x.titleName, value: x.titleID }
                        });
                        this.formItems[2].itemRender.props.disabled = true;
                        resolve();
                    }).catch(() => {
                        resolve();
                    });
                });
            },
            getData(type) { // 获取用户列表
                if (type === 0) {
                    this.tablePage.currentPage = 1;
                }
                this.loading = true;
                var whereStr = "1 = 1 ";

                if (!!this.searchName) {
                    whereStr += " and userName like '%" + this.searchName.trim() + "%' ";
                }
                baseAPI.getUserList({
                    pageIndex: this.tablePage.currentPage - 1,
                    pageSize: this.tablePage.pageSize,
                    where: whereStr,
                }).then(res => {
                    this.tableData = res.result;
                    this.tablePage.total = res.recordCount;
                    this.loading = false;
                }).catch(() => {
                    this.loading = false;
                });
            },
            handlePageChange({ currentPage, pageSize }) {
                this.tablePage.currentPage = currentPage;
                this.tablePage.pageSize = pageSize;
                this.getData();
            },
            editClosed({ row, rowIndex }) {
                this.$refs.xGrid.validate().then(suc => {
                    if (!suc) {
                        baseAPI.update(row).then(res => {
                            this.$message({ type: 'success', message: '修改成功' });
                            this.getData();
                        }).catch(err => { });
                    }
                }).catch(err => { });
            },

            create() {
                this.formTitle = '新增用户';
                this.fileList = [];
                this.titleLevelOption = [];
                this.signFrontInfo = '';
                this.formInfo = {
                    birthday: '',
                    password: '',
                    realName: '',
                    sex: true,
                    userCode: '',
                    userName: '',
                    roleId: null,
                    isDelete: false,
                };
                this.showCreate = true;
            },
            edit(row) {
                this.formTitle = '编辑用户信息';
                this.showCreate = true;
                this.formLoading = true;
                this.fileList = [];
                this.titleLevelOption = [];
                this.signFrontInfo = '';
                baseAPI.getUserByID(row.userID).then(res => {
                    this.formInfo = res;
                    this.formLoading = false;
                    //this.getTitle();
                });
            },
            deleteDe(row) {
                this.$confirm(`是否删除用户 ${row.userName}`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.loading = true;
                    baseAPI.deleteDaUser(row.userID).then(res => {
                        if (!res) {
                            this.$message({ type: 'warning', message: '删除失败!' });
                        }
                        this.$message({ type: 'success', message: '删除成功!' });
                        this.getData(0);
                    });
                }).catch(() => {
                    this.loading = false;
                });
            },
            save() {
                this.$refs.myform.validate().then(suc => {
                    if (!suc) {
                        
                        this.formInfo.userID ? this.isAdd = true : this.isAdd = false;
                        this.formLoading = true;
                        console.log(this.formInfo)

                        baseAPI[this.formInfo.userID ? 'updateUser' : 'createUser'](this.formInfo).then(res => {
                            if (res) {
                                this.$message({ type: 'success', message: this.isAdd ? '修改成功' : '创建成功' });
                                this.formLoading = false;
                                this.showCreate = false;
                                this.getData(0);
                            } else {
                                this.$message({ type: 'warning', message: this.isAdd ? '修改失败' : '创建失败' });
                                this.formLoading = false;
                                this.showCreate = false;
                                this.getData(0);
                            }

                        }).catch(err => {
                            this.formLoading = false;
                        });
                    }
                }).catch(() => { });
            },
            selectTitle() {
                this.formInfo.titleID = '';
                this.getTitle();
            },
            getTitle() {
                this.titleLevelOption = [];
                var data = {
                    lvl: this.formInfo.titleLevel
                };
                baseAPI.getTitleByLevel(data).then(res => {
                    this.titleLevelOption = res.map(x => {
                        return { label: x.titleName, value: x.titleID }
                    });
                    this.formLoading = false;
                }).catch(() => {
                });
            },
            goBack() {
                this.showCreate = false;
                this.$refs.myform.reset();
                this.getData(0);
            },

            format(ops, op, hasops) {
                var val = null;
                if (hasops) {
                    var options = ops.map(e => {
                        return e.options;
                    }).flat().valueOf();
                    val = options.find(e => e.value === op);
                } else {
                    val = ops.find(e => e.value === op);
                }
                return val ? val.label : '';
            },
            toDate(date) {
                return date ? moment(date).format("YYYY-MM-DD") : '';
            }
        },
        template: "#template"
    };
</script>
